﻿using System;
using System.Reflection;

namespace GamepadDriver
{
	public static class ObjectExtensions
	{
		public static void FireEvent(this object @this, string eventName, params object[] parameters)
		{
			var type = @this.GetType();

			var eventFieldInfo = type.GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic);
			if (eventFieldInfo == null)
			{
				return;
			}

			var eventDelegate = eventFieldInfo.GetValue(@this) as MulticastDelegate;
			if (eventDelegate == null)
			{
				return;
			}

			var delegates = eventDelegate.GetInvocationList();
			foreach (var dlg in delegates)
			{
				dlg.Method.Invoke(dlg.Target, parameters);
			}
		}
	}
}